package com.util;

import com.constant.Constant;
import com.sun.org.glassfish.gmbal.ManagedData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author YZK
 * @Date 2023/10/19
 */
public class FileUtils {
    /***
     *  获取本地文件的大小
     * @param path 文件路径
     * @return 文件大小
     */
    public static long getFileContentLength(String path) {
        File file = new File(path);
        return file.exists() && file.isFile() ? file.length() : 0;
    }

    /***
     *  获取文件MD5值
     * @param filePath 文件路径
     * @return boolean
     */
    public static String getFileMD5(String filePath) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream(filePath);
        byte[] buffer = new byte[Constant.BYTE_SIZE];
        int length;
        while ((length = fis.read(buffer)) != -1) {
            md.update(buffer, 0, length);
        }
        fis.close();
        byte[] digest = md.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        return bigInt.toString(16);
    }

    /***
     * 比较文件MD5
     * @param filePath1 文件1的路径
     * @param filePath2 文件2的路径
     * @return boolean
     */
    public static boolean verifyFileMD5(String filePath1, String filePath2) throws IOException, NoSuchAlgorithmException {
        String file1MD5 = getFileMD5(filePath1);
        String file2MD5 = getFileMD5(filePath2);
        return file1MD5.equals(file2MD5);
    }
}